package com.foton.mybatis.factory;

import com.foton.mybatis.model.MappedStatement;
import com.foton.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * @Author RenPu
 * @Date 2023/3/30 17:01
 * @Version 1.0
 * @Description:
 **/
public class MapperProxy<T> implements InvocationHandler {

    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface) {
        this.mapperInterface=mapperInterface;
        this.sqlSession=sqlSession;
    }




    @Override
    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
      if(Object.class.equals(method.getDeclaringClass())){
          return method.invoke(this,args);
      }

      return this.excute(method,args);
    }



    private Object excute(Method method, Object[] args) {

        String stamentedId=this.mapperInterface.getName()+"."+method.getName();
        MappedStatement ms=this.sqlSession.getConfigration().getMappedStatement(stamentedId);
        Object result=null;
        switch (ms.getSqlcommondType()){
            case SELECT:{
                Class<?> returnType = method.getReturnType();
                if(Collection.class.equals(returnType)){
                    result=this.sqlSession.selectList(stamentedId,args);
                }else {
                    this.sqlSession.selectOne(stamentedId,args);
                }
                break;
            }
            case UPDATE:{
                sqlSession.upate(stamentedId,args);
                break;
            }
            default:{
                //TODO 执行其他的业务逻辑
                break;
            }

        }



       return null;
    }
}
